<template>
  <div class="course-detail">
    <div class="banner">
      <h1>课程详情</h1>
    </div>

    <el-row class="content-row">
      <el-col :span="6" class="menu-column">
        <el-collapse>
          <el-collapse-item title="课程信息" name="1">
            <el-menu>
              <el-menu-item @click="setCurrentContent('description')">课程介绍</el-menu-item>
              <el-menu-item @click="setCurrentContent('syllabus')">教学大纲</el-menu-item>
              <el-menu-item @click="setCurrentContent('calendar')">教学日历</el-menu-item>
            </el-menu>
          </el-collapse-item>

          <el-collapse-item title="课程资源" name="2">
            <el-menu>
              <el-menu-item @click="setCurrentContent('resources')">电子课件</el-menu-item>
            </el-menu>
          </el-collapse-item>

          <el-collapse-item title="课程考核" name="4">
            <el-menu>
              <el-menu-item @click="setCurrentContent('homework')">作业</el-menu-item>
              <el-menu-item @click="setCurrentContent('exam')">结课考核</el-menu-item>
            </el-menu>
          </el-collapse-item>

          <el-collapse-item title="答疑讨论" name="5">
            <el-menu>
              <el-menu-item @click="setCurrentContent('discussion')">答疑讨论</el-menu-item>
            </el-menu>
          </el-collapse-item>
        </el-collapse>
      </el-col>

      <el-col :span="18" class="content-column">
        <div class="course-content">
          <h2>{{ currentTitle }}</h2>
          <component :is="currentComponent" v-if="currentComponent === 'PostList'" :course_id="course_id"></component>
          <div v-if="isEditing">
            <el-input v-model="editContent" type="textarea" rows="5"></el-input>
            <el-button type="primary" @click="saveContent(currentContentType)">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </div>
          <div v-else>
            <p>{{ currentContent }}</p>
            <div v-if="currentContent === '考核'" class="exam-actions">
              <!-- 结课考核部分 -->
              <el-table
                  v-if="Array.isArray(examAssignments) && examAssignments.length > 0"
                  :data="examAssignments"
                  stripe
                  style="width: 100%; margin-top: 20px;"
              >
                <el-table-column prop="exam_name" label="考试" width="150"   />
                <el-table-column prop="date" label="考试日期" width="150" :formatter="formatDate"  />
                <el-table-column prop="time" label="时间段" width="150" />
                <el-table-column prop="class_id" label="考试教室" width="150" />
                <el-table-column prop="seat" label="考试座位" width="150" />
<!--                <el-table-column label="操作" width="180">-->
<!--                  <template v-slot="scope">-->
<!--                    <el-button size="mini" type="primary" @click="gotoSubmitExam(scope.row.exam_id)">-->
<!--                      提交答案-->
<!--                    </el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
              </el-table>

              <!-- 分页 -->
              <el-row style="margin-top: 20px; justify-content: center;">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="examAssignments.length"
                    :page-size="pageSize"
                    @current-change="handleExamPageChange"
                />
              </el-row>
            </div>

            <el-list v-if="currentContent === '这是电子课件的详细内容。' && files.length > 0">
              <el-list-item v-for="file in files" :key="file.id" style="margin-bottom: 10px;">
                <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                  <span>{{ file.fileName }}</span>
                  <el-button @click="downloadFile(file.id)" type="primary" size="mini">下载</el-button>
                </div>
              </el-list-item>
            </el-list>

            <!-- 作业表格部分 -->
            <div v-if="currentContent === '作业'" class="assignments-table">
              <el-row style="margin-top: 40px;">
                <el-table
                    :data="paginatedAssignmentsWithEmptyRows"
                    :default-sort="{ prop: 'dueDate', order: 'descending' }"
                    stripe
                    style="width: 100%"
                    :row-style="setRowHeight"
                >
                  <el-table-column prop="dueDate" label="截止日期" width="180" />
                  <el-table-column prop="title" label="作业标题" width="180" />
                  <el-table-column prop="content" label="作业内容" />
                  <el-table-column label="操作" width="280">
                    <template v-slot="scope">
<!--                      <div style="display: flex; gap: 5px;">-->
                      <div style="display: flex; justify-content: flex-start; gap: 10px;">
                        <el-button
                            v-if="scope.row.homework_id"
                            size="mini"
                            type="primary"
                            @click="viewDetails(scope.row)"
                            class="view-button"
                        >
                          查看详情
                        </el-button>
                        <el-button
                            v-if="scope.row.homework_id"
                            size="mini"
                            @click="submitAssignment(scope.row)"
                            class="submit-button"
                        >
                          提交作业
                        </el-button>
                        <el-button
                            v-if="scope.row.id !== null"
                            size="mini"
                            @click="reviewAssignment(scope.row)"
                            class="submit-button"
                        >
                          作业互评
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>

              <!-- 分页 -->
              <el-row style="margin-top: 20px; justify-content: center;">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="this.assignments.length"
                    :page-size="pageSize"
                    @current-change="handlePageChange"
                />
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios';
import PostList from '@/components/Post/PostList.vue';
import { BASE_URL } from '@/config';

export default {
  components: {
    PostList,
  },
  data() {
    return {
      currentContent: '',
      currentTitle: '',
      files: [],
      assignments: [], // 作业列表
      currentPage: 1,
      pageSize: 10,
      examAssignments: [], // 考试数据
      selectedAssignment: {},
      isDialogVisible: false,
      isEditing: false,
      editContent: '',
      course_id: null, // 使用null来标记未初始化的整数
      currentComponent: null,
      currentContentType: '',
    };
  },
  created() {
    // 获取路由参数中的 course_id
    this.course_id = parseInt(this.$route.params.course_id, 10); // 将 course_id 转换为整数
    console.log("Initialized course_id from route:", this.course_id);

    // 页面加载时默认显示“课程介绍”
    this.setCurrentContent('description');
  },
  methods: {
    formatDate(row, column, cellValue) {
      // 截取日期前10位，假设日期格式为 'YYYY-MM-DD HH:mm:ss'
      return cellValue ? cellValue.substring(0, 10) : '';
    },
    async fetchContent(endpoint) {
      try {
        console.log("Fetching content for endpoint:", endpoint);
        console.log("Current course_id value:", this.course_id);

        const response = await axios.post(`${BASE_URL}/course/${endpoint}`, {
          course_id: this.course_id,
        });
        this.currentContent = response.data.data; // 假设返回数据中有 content 字段
      } catch (error) {
        console.error(`获取${endpoint}失败:`, error);
      }
    },
    async setCurrentContent(content) {
      this.currentContentType = content;
      console.log("Setting current content to:", content);
      this.currentContent = '';
      this.currentComponent = null;

      if (content === 'resources') {
        this.currentTitle = '电子课件';
        this.currentContent = '这是电子课件的详细内容。';
        await this.fetchFiles();
      } else if (content === 'discussion') {
        this.currentComponent = 'PostList';
      } else if (content === 'homework') {
        this.currentTitle = '作业';
        this.currentContent = '作业';
        await this.fetchAssignments();  // 获取作业数据
      } else if (content === 'exam') {
        this.currentTitle = '考核';
        this.currentContent = '考核';
        await this.fetchExamAssignments();  // 获取考试数据
      } else {
        this.currentTitle = content === 'description' ? '课程介绍' :
            content === 'syllabus' ? '教学大纲' :
                content === 'calendar' ? '教学日历' : '';

        await this.fetchContent(content);
      }
    },
    async fetchFiles() {
      try {
        const response = await axios.post(`${BASE_URL}/files/fileList`, {
          course_id: this.course_id,
        });
        if (response.data && response.data.code === 200) {
          this.files = response.data.data;
        } else {
          this.$message.error('获取文件列表失败');
        }
      } catch (error) {
        console.error('获取文件列表请求失败:', error);
      }
    },
    async fetchExamAssignments() {
      try {
        const response = await axios.post(`${BASE_URL}/exam/stuExamList`, {
          course_id: this.course_id,
          stu_id:window.sessionStorage.getItem('userId'),
        });

        if (response.data.code === 200) {
          const examData = response.data.data;

          // 确保 examData 是数组
          if (Array.isArray(examData)) {
            this.examAssignments = examData;
          } else {
            console.error('后端返回数据不是数组:', examData);
            this.examAssignments = [];
            this.$message.error('获取考试数据失败：数据格式错误');
          }
        } else {
          this.$message.error('获取考试数据失败');
        }
      } catch (error) {
        console.error('获取考试数据失败:', error);
        this.$message.error('获取考试数据失败');
      }
    },
    viewDetails(assignment) { //查看作业详情
      this.$router.push({ name: 'AssignmentDetail', params: { homework_id: assignment.homework_id , title: assignment.title} });
    },
    setRowHeight() { //作业列表高度
      return { height: '50px' };
    },
    // 下载文件
    async downloadFile(fileId) {
      try {
        // 发送 POST 请求
        const response =await axios.post(
            `${BASE_URL}/files/download`,
            {
              id: fileId,
            }
        );

        // 假设后端返回的数据是 Base64 格式
        const base64Data = response.data.data.file; // 确保 data 是 Base64 字符串
        const mimeType = "application/pdf"; // 设置文件的 MIME 类型
        const blob = this.base64ToBlob(base64Data, mimeType);
        const name = response.data.data.fileName

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;

        // 设置文件名
        link.setAttribute("download", `${name}`);
        document.body.appendChild(link);
        link.click();

        // 清理资源
        link.remove();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error("文件下载失败:", error);
        this.$message.error("文件下载失败");
      }
    },

// Base64 转 Blob 工具函数
    base64ToBlob(base64, mimeType) {
      const byteCharacters = atob(base64); // 解码 Base64
      const byteNumbers = new Array(byteCharacters.length)
          .fill(0)
          .map((_, i) => byteCharacters.charCodeAt(i));
      const byteArray = new Uint8Array(byteNumbers);
      return new Blob([byteArray], { type: mimeType });
    },
    submitAssignment(assignment) { //提交作业
      const stu_id = window.sessionStorage.getItem('userId')
      this.$router.push({
        name: 'AssignmentSubmit',
        query: {
          stu_id: stu_id,
          homework_id: assignment.homework_id,
          title: assignment.title, // 传递作业标题
          content: assignment.content // 传递作业内容
        }
      });
    },
    gotoSubmitExam(exam_id){
      console.log("提交考试id",exam_id);
      this.$router.push({name: 'SubmitExam', query: {exam_id:exam_id}});
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    async fetchAssignments() {
      try {
        const response = await axios.post(`${BASE_URL}/homework/gethomework`, { course_id: this.course_id });
        console.log('API 返回的数据:', response.data);

        if (response.data && response.data.code === 200) {
          this.assignments = response.data.data.map(item => ({
            homework_id: item.homework_id,
            title: item.title || '未提供标题',
            content: item.content || '无内容',
            dueDate: item.due_date || '无截止日期',
            course_id: item.course_id || '未指定课程'
          }));
        } else {
          console.error('获取作业列表失败，API 返回错误:', response.data.message);
        }
      } catch (error) {
        console.error('获取作业列表请求失败:', error);
      }
    },

    reviewAssignment(assignment) {
      console.log(assignment)
      console.log("作业id:", assignment.homework_id, "课程id:", assignment.course_id);
      if (!assignment.homework_id || !assignment.course_id) {
        this.$message.error("作业 ID 或课程 ID 缺失，无法跳转到互评页面！");
        return;
      }
      this.$router.push({
        name: 'ReviewAssignment', // 路由名称
        query: {
          homework_id: assignment.homework_id,
          course_id: assignment.course_id
        } // 传递参数
      });
    },
    async saveContent(content) {
      try {
        console.log("传递前："+this.editContent)
        if(content === 'calendar') {
          await axios.put(`${BASE_URL}/course/update${content}`, {course_id: this.course_id, calendar: this.editContent,});
        }
        if(content === 'description') {
          await axios.put(`${BASE_URL}/course/update${content}`, {course_id: this.course_id, course_description: this.editContent,});
        }
        if(content === 'syllabus') {
          await axios.put(`${BASE_URL}/course/update${content}`, {course_id: this.course_id, syllabus: this.editContent,});
        }
        this.currentContent = this.editContent;
        console.log("修改后："+this.editContent)
        this.isEditing = false;
        this.$message.success('保存成功');
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败');
      }
    },
    cancelEdit() {
      this.isEditing = false;
    },
  },
  computed: {
    paginatedAssignments() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.assignments.slice(start, end);
    },
    paginatedAssignmentsWithEmptyRows() {
      const assignmentsPage = this.paginatedAssignments;
      const emptyRows = Array(this.pageSize - assignmentsPage.length).fill({
        dueDate: '',
        title: '',
        content: '',
        id: null,
      });
      return [...assignmentsPage, ...emptyRows];
    },
  },
};
</script>

<style scoped>
.course-detail {
  padding: 20px;
  background-color: #f5f5f5;
}

.banner {
  background-color: #3f51b5;
  color: white;
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.content-row {
  margin: 0;
}

.menu-column {
  padding: 0 10px;
}

.content-column {
  padding: 0 10px;
}

.course-content {
  padding: 20px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.assignments-table {
  margin-top: 20px;
}

.assignments-table .el-table th, .assignments-table .el-table td {
  text-align: center;
}

.view-button {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 12px;
  border: none;
}

.view-button:hover {
  background-color: #66b1ff;
}

.submit-button {
  background-color: white;
  color: #409eff;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 12px;
}

.submit-button:hover {
  background-color: #f0f0f0;
}
</style>
